
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

using namespace std;

namespace {

std::mutex iomt;
void output(int i)
{
	std::lock_guard<std::mutex> lk(iomt);
	cout << i << endl;
}

// 线程RAII形式关联主线程
class thread_guard
{
	thread &t;
public :
	explicit thread_guard(thread& _t) : t(_t){}

	~thread_guard()
	{
		if (t.joinable())
			t.join();
	}

	thread_guard(const thread_guard&) = delete;
	thread_guard& operator=(const thread_guard&) = delete;
};

void func(){

	// 线程变量创建后，子线程立即执行
	thread t([]{
		cout << "Hello thread" <<endl ;
	});

	thread_guard g(t);
    t.detach();
}

void Handle() {

	for (uint8_t i = 0; i < 4; i++)
	{
		thread t(output, i);
		// detach脱离主线程运行，否在t会被销毁时，子线程还在运行会报错
		t.detach();
	}

    func();

	thread t1(output, 100);
	thread t2(output, 200);
	thread t3(output, 300);

	// 如果不join或者detach，可能thead数据已销毁，子线程还在运行，
	// 则会报错：terminate called without an active exception
	t1.join();
	t2.join();
	t3.join();

	getchar();
}

}

void HandleThread() {
    Handle();
}
